<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{#if isNew}}新建{{else}}编辑{{/if}}服务台配置 {{config.mer_code}}</title>
    <script src="/apps/js/baidu-tongji-mtx.js"></script>
    <link rel="stylesheet" href="/apps/css/bootstrap.min.css">
    <link href="/apps/css/fontawesome-free-6.4.0-web/css/all.css" rel="stylesheet">
    <style>
        .form-text { font-size: 0.9rem; }
        .service-group-card { border-radius: 1rem; box-shadow: 0 2px 16px rgba(0,0,0,0.07); }
        .service-item-card { border-radius: 0.75rem; transition: box-shadow 0.2s; }
        .service-item-card:hover { box-shadow: 0 4px 24px rgba(0,0,0,0.13); }
        .avatar-preview, .qrcode-preview { width: 48px; height: 48px; object-fit: cover; border-radius: 0.5rem; border: 1px solid #eee; background: #fafbfc; }
        .add-group-btn, .add-service-btn { transition: box-shadow 0.2s, transform 0.2s; }
        .add-group-btn:hover, .add-service-btn:hover { box-shadow: 0 2px 8px #19875444; transform: translateY(-2px) scale(1.04); }
        .remove-group-btn, .remove-service-btn { transition: background 0.2s; }
        .remove-group-btn:hover, .remove-service-btn:hover { background: #dc3545 !important; color: #fff !important; }
        .required-star { color: #dc3545; margin-left: 2px; }
        .card-header { border-radius: 1rem 1rem 0 0 !important; }
        .collapse-toggle { cursor: pointer; }
        @media (max-width: 768px) {
            .service-item-card { margin-bottom: 1rem; }
        }
        .dragging {
            opacity: 0.5;
            box-shadow: 0 0 16px #0d6efd55 !important;
        }
    </style>
</head>
<body>
<div class="container py-4">
    <h2 class="mb-4 text-center">{{#if isNew}}新建{{else}}编辑{{/if}}服务台配置 {{config.mer_code}}</h2>
    <form action="/apps/helpdesk/save" method="POST" id="configForm">
        <input type="hidden" name="mer_code" value="{{config.mer_code}}">
        <input type="hidden" name="groups" id="groupsInput">
        <div class="row mb-4">
            <div class="col-md-6 mb-3">
                <label for="merchant_name" class="form-label">商户名称 <span class="required-star">*</span></label>
                <input type="text" class="form-control" id="merchant_name" name="merchant_name" value="{{config.merchant_name}}" required>
            </div>
            <div class="col-md-6 mb-3">
                <label for="phone" class="form-label">客服电话 <span class="required-star">*</span></label>
                <input type="text" class="form-control" id="phone" name="phone" value="{{config.phone}}" required>
            </div>
        </div>
        <div id="groupsArea">
            {{#each config.groups}}
            <div class="card mb-4 service-group-card" data-group-index="{{@index}}">
                <div class="card-header d-flex justify-content-between align-items-center bg-primary text-white">
                    <div class="d-flex align-items-center">
                        <span class="fs-5 group-title">{{this.group_name}}</span>
                        <input type="text" class="form-control ms-3 group-name-input bg-light text-dark" value="{{this.group_name}}" placeholder="分组名称" required style="width:180px;">
                    </div>
                    <div>
                        <button type="button" class="btn btn-danger btn-sm rounded-circle remove-group-btn" title="删除分组"><i class="fa fa-trash"></i></button>
                        <button type="button" class="btn btn-light btn-sm rounded-circle ms-2 collapse-toggle" title="收起/展开"><i class="fa fa-chevron-down"></i></button>
                    </div>
                </div>
                <div class="card-body group-body">
                    <div class="row g-3 services-container">
                        {{#each this.services}}
                        <div class="col-md-4">
                            <div class="card service-item-card shadow-sm mb-3" data-service-index="{{@index}}">
                                <div class="card-body">
                                    <div class="mb-2 d-flex align-items-center">
                                        <span class="me-2">ID <span class="required-star">*</span></span>
                                        <input type="text" class="form-control service-id-input" value="{{this.id}}" placeholder="客服手机号" required>
                                    </div>
                                    <div class="mb-2 d-flex align-items-center">
                                        <span class="me-2">姓名<span class="required-star">*</span></span>
                                        <input type="text" class="form-control service-title-input" value="{{this.title}}" required>
                                    </div>
                                    <div class="mb-2 d-flex align-items-center">
                                        <span class="me-2">状态</span>
                                        <select class="form-select service-status-select" style="width:auto;">
                                            <option value="online" {{#if (eq this.status "online")}}selected{{/if}}>在线</option>
                                            <option value="offline" {{#if (eq this.status "offline")}}selected{{/if}}>离线</option>
                                        </select>
                                    </div>
                                    <div class="mb-2 d-flex align-items-center">
                                        <span class="me-2">头像</span>
                                        <div class="input-group align-items-center">
                                            <input type="text" class="form-control service-avatar-input" value="{{this.avatar}}" placeholder="图片链接">
                                            <button class="btn btn-outline-secondary" type="button" onclick="handleImageUpload(this, 'avatar')"><i class="fa fa-upload"></i></button>
                                            <img class="img-thumbnail ms-2 avatar-preview" style="width:48px;height:48px;display:{{#if this.avatar}}inline-block{{else}}none{{/if}};" src="{{this.avatar}}" onerror="this.style.display='none'">
                                        </div>
                                    </div>
                                    <div class="mb-2 d-flex align-items-center">
                                        <span class="me-2">描述</span>
                                        <input type="text" class="form-control service-desc-input" value="{{this.desc}}">
                                    </div>
                                    <div class="mb-2 d-flex align-items-center">
                                        <span class="me-2">联系</span>
                                        <div class="input-group align-items-center">
                                            <input type="text" class="form-control service-qrcode-input" value="{{this.qrcode}}" placeholder="二维码图片链接">
                                            <button class="btn btn-outline-secondary" type="button" onclick="handleImageUpload(this, 'qrcode')"><i class="fa fa-upload"></i></button>
                                            <img class="img-thumbnail ms-2 qrcode-preview" style="width:48px;height:48px;display:{{#if this.qrcode}}inline-block{{else}}none{{/if}};" src="{{this.qrcode}}" onerror="this.style.display='none'">
                                        </div>
                                    </div>
                                    <div class="mb-2 d-flex align-items-center">
                                        <span class="me-2">提示</span>
                                        <input type="text" class="form-control service-tip-input" value="{{this.tip}}">
                                    </div>
                                    <div class="mb-2 d-flex align-items-center">
                                        <span class="me-2">链接</span>
                                        <input type="text" class="form-control service-link-input" placeholder="提示跳转链接（可为空）">
                                        <button type="button" class="btn btn-link ms-2 service-link-jump" style="display:none;" tabindex="-1">跳转</button>
                                    </div>
                                    <div class="form-text service-link-tip" style="display:none;">如果是有效链接，点击"跳转"按钮可访问</div>
                                    <div class="text-end mt-2">
                                        <button type="button" class="btn btn-outline-danger btn-sm rounded-circle remove-service-btn" title="删除客服"><i class="fa fa-trash"></i></button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {{/each}}
                    </div>
                    <div class="text-center mt-3">
                        <button type="button" class="btn btn-outline-success add-service-btn"><i class="fa fa-plus"></i> 添加客服</button>
                    </div>
                </div>
            </div>
            {{/each}}
        </div>
        <div class="text-center my-4">
            <button type="button" class="btn btn-success btn-lg rounded-pill shadow add-group-btn"><i class="fa fa-plus"></i> 添加新分组</button>
        </div>
        <div class="row">
            <div class="col-md-12 d-flex justify-content-between">
                <a href="/apps/helpdesk/ihealthify/{{config.mer_code}}" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left"></i> 返回列表
                </a>
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save"></i> 保存并预览
                </button>
            </div>
        </div>
    </form>
</div>
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js" defer></script>
<script src="/apps/js/bootstrap.bundle.min.js" defer></script>
<script src="/apps/js/wx-client-dom.js" defer></script>
<script>
// 最强保险：只保留id=groupsInput的name=groups，其余全部移除
    document.addEventListener('DOMContentLoaded', function() {
        document.querySelectorAll('input[name="groups"],select[name="groups"]').forEach(el => {
            if (el.id !== 'groupsInput') el.removeAttribute('name');
        });
        // 分组折叠/展开
        document.addEventListener('click', function(e) {
            if (e.target.closest('.collapse-toggle')) {
                const groupCard = e.target.closest('.service-group-card');
                const groupBody = groupCard.querySelector('.group-body');
                groupBody.classList.toggle('d-none');
                e.target.classList.toggle('fa-chevron-down');
                e.target.classList.toggle('fa-chevron-up');
            }
        });
        // 拖拽排序功能
        function initDragSort() {
            // 分组卡片拖拽
            function getDragAfterElement(container, y, selector) {
                const draggableElements = [...container.querySelectorAll(selector + ':not(.dragging)')];
                return draggableElements.reduce((closest, child) => {
                    const box = child.getBoundingClientRect();
                    const offset = y - box.top - box.height / 2;
                    if (offset < 0 && offset > closest.offset) {
                        return { offset: offset, element: child };
                    } else {
                        return closest;
                    }
                }, { offset: -Infinity }).element;
            }
            // 分组
            let draggingGroup = null;
            document.querySelectorAll('.service-group-card').forEach(card => {
                card.setAttribute('draggable', 'true');
                card.addEventListener('dragstart', function(e) {
                    draggingGroup = this;
                    this.classList.add('dragging');
                });
                card.addEventListener('dragover', function(e) {
                    e.preventDefault();
                    const groupsArea = document.getElementById('groupsArea');
                    const after = getDragAfterElement(groupsArea, e.clientY, '.service-group-card');
                    if (after == null) {
                        groupsArea.appendChild(draggingGroup);
                    } else {
                        groupsArea.insertBefore(draggingGroup, after);
                    }
                });
                card.addEventListener('drop', function(e) {
                    this.classList.remove('dragging');
                    draggingGroup = null;
                });
                card.addEventListener('dragend', function(e) {
                    this.classList.remove('dragging');
                    draggingGroup = null;
                });
            });
            // 客服卡片拖拽
            document.querySelectorAll('.services-container').forEach(container => {
                let draggingService = null;
                container.querySelectorAll('.service-item-card').forEach(card => {
                    card.setAttribute('draggable', 'true');
                    card.addEventListener('dragstart', function(e) {
                        draggingService = this;
                        this.classList.add('dragging');
                    });
                    card.addEventListener('dragover', function(e) {
                        e.preventDefault();
                        const after = getDragAfterElement(container, e.clientY, '.service-item-card');
                        if (after == null) {
                            container.appendChild(draggingService);
                        } else {
                            container.insertBefore(draggingService, after);
                        }
                    });
                    card.addEventListener('drop', function(e) {
                        this.classList.remove('dragging');
                        draggingService = null;
                    });
                    card.addEventListener('dragend', function(e) {
                        this.classList.remove('dragging');
                        draggingService = null;
                    });
                });
            });
        }
        // 初始化拖拽排序（初始和每次添加分组/客服后都要调用）
        initDragSort();
        // 添加分组
        document.querySelector('.add-group-btn').addEventListener('click', function() {
            const groupsArea = document.getElementById('groupsArea');
            const groupIndex = groupsArea.querySelectorAll('.service-group-card').length;
            const groupHtml = `
            <div class="card mb-4 service-group-card" data-group-index="${groupIndex}">
                <div class="card-header d-flex justify-content-between align-items-center bg-primary text-white">
                    <div class="d-flex align-items-center">
                        <span class="fs-5 group-title">新分组</span>
                        <input type="text" class="form-control ms-3 group-name-input bg-light text-dark" value="" placeholder="分组名称" required style="width:180px;">
                    </div>
                    <div>
                        <button type="button" class="btn btn-danger btn-sm rounded-circle remove-group-btn" title="删除分组"><i class="fa fa-trash"></i></button>
                        <button type="button" class="btn btn-light btn-sm rounded-circle ms-2 collapse-toggle" title="收起/展开"><i class="fa fa-chevron-down"></i></button>
                    </div>
                </div>
                <div class="card-body group-body">
                    <div class="row g-3 services-container"></div>
                    <div class="text-center mt-3">
                        <button type="button" class="btn btn-outline-success add-service-btn"><i class="fa fa-plus"></i> 添加客服</button>
                    </div>
                </div>
            </div>`;
            groupsArea.insertAdjacentHTML('beforeend', groupHtml);
            initDragSort();
        });
        // 删除分组
        document.addEventListener('click', function(e) {
            if (e.target.closest('.remove-group-btn')) {
                e.target.closest('.service-group-card').remove();
            }
        });
        // 添加客服
        document.addEventListener('click', function(e) {
            if (e.target.closest('.add-service-btn')) {
                const servicesContainer = e.target.closest('.group-body').querySelector('.services-container');
                const serviceIndex = servicesContainer.querySelectorAll('.service-item-card').length;
                const serviceHtml = `
                <div class="col-md-4">
                    <div class="card service-item-card shadow-sm mb-3" data-service-index="${serviceIndex}">
                        <div class="card-body">
                            <div class="mb-2 d-flex align-items-center">
                                <span class="me-2">ID <span class="required-star">*</span></span>
                                <input type="text" class="form-control service-id-input" value="" placeholder="请输入ID" required>
                            </div>
                            <div class="mb-2 d-flex align-items-center">
                                <span class="me-2">客服名称 <span class="required-star">*</span></span>
                                <input type="text" class="form-control service-title-input" required>
                            </div>
                            <div class="mb-2 d-flex align-items-center">
                                <span class="me-2">状态</span>
                                <select class="form-select service-status-select" style="width:auto;">
                                    <option value="online">在线</option>
                                    <option value="offline">离线</option>
                                </select>
                            </div>
                            <div class="mb-2 d-flex align-items-center">
                                <span class="me-2">头像</span>
                                <div class="input-group align-items-center">
                                    <input type="text" class="form-control service-avatar-input" placeholder="图片链接">
                                    <button class="btn btn-outline-secondary" type="button" onclick="handleImageUpload(this, 'avatar')"><i class="fa fa-upload"></i></button>
                                    <img class="img-thumbnail ms-2 avatar-preview" style="width:48px;height:48px;display:none;" onerror="this.style.display='none'">
                                </div>
                            </div>
                            <div class="mb-2 d-flex align-items-center">
                                <span class="me-2">描述</span>
                                <input type="text" class="form-control service-desc-input">
                            </div>
                            <div class="mb-2 d-flex align-items-center">
                                <span class="me-2">提示语</span>
                                <input type="text" class="form-control service-tip-input">
                            </div>
                            <div class="mb-2 d-flex align-items-center">
                                <span class="me-2">二维码</span>
                                <div class="input-group align-items-center">
                                    <input type="text" class="form-control service-qrcode-input" placeholder="二维码图片链接">
                                    <button class="btn btn-outline-secondary" type="button" onclick="handleImageUpload(this, 'qrcode')"><i class="fa fa-upload"></i></button>
                                    <img class="img-thumbnail ms-2 qrcode-preview" style="width:48px;height:48px;display:none;" onerror="this.style.display='none'">
                                </div>
                            </div>
                            <div class="mb-2 d-flex align-items-center">
                                <span class="me-2">链接</span>
                                <input type="text" class="form-control service-link-input" placeholder="相关链接">
                                <button type="button" class="btn btn-link ms-2 service-link-jump" style="display:none;" tabindex="-1">跳转</button>
                            </div>
                            <div class="form-text service-link-tip" style="display:none;">如果是有效链接，点击"跳转"按钮可访问</div>
                            <div class="text-end mt-2">
                                <button type="button" class="btn btn-outline-danger btn-sm rounded-circle remove-service-btn" title="删除客服"><i class="fa fa-trash"></i></button>
                            </div>
                        </div>
                    </div>
                </div>`;
                servicesContainer.insertAdjacentHTML('beforeend', serviceHtml);
                setTimeout(initDragSort, 0);
            }
        });
        // 删除客服
        document.addEventListener('click', function(e) {
            if (e.target.closest('.remove-service-btn')) {
                const card = e.target.closest('.col-md-4');
                card.remove();
            }
        });
        // 头像/二维码/链接即时预览
        document.addEventListener('input', function(e) {
            if (e.target.classList.contains('service-avatar-input')) {
                const url = e.target.value;
                const img = e.target.closest('.input-group').querySelector('.avatar-preview');
                if (url && /^https?:\/\//.test(url)) {
                    img.src = url;
                    img.style.display = '';
                } else {
                    img.style.display = 'none';
                }
            }
            if (e.target.classList.contains('service-qrcode-input')) {
                const url = e.target.value;
                const img = e.target.closest('.input-group').querySelector('.qrcode-preview');
                if (url && /^https?:\/\//.test(url)) {
                    img.src = url;
                    img.style.display = '';
                } else {
                    img.style.display = 'none';
                }
            }
            if (e.target.classList.contains('service-link-input')) {
                const url = e.target.value.trim();
                const btn = e.target.parentElement.querySelector('.service-link-jump');
                const tip = e.target.parentElement.parentElement.querySelector('.service-link-tip');
                if (/^https?:\/\//.test(url)) {
                    btn.style.display = '';
                    btn.onclick = function() { window.open(url, '_blank'); };
                    if (tip) tip.style.display = '';
                } else {
                    btn.style.display = 'none';
                    btn.onclick = null;
                    if (tip) tip.style.display = 'none';
                }
            }
        });
        // 表单提交，组装完整对象
        const phoneReg = /^1[3-9]\d{9}$/;
        document.getElementById('configForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const groups = [];
            let valid = true;
            document.querySelectorAll('.service-group-card').forEach(groupEl => {
                const group = {
                    group_name: groupEl.querySelector('.group-name-input').value,
                    services: []
                };
                groupEl.querySelectorAll('.service-item-card').forEach(serviceEl => {
                    const idVal = serviceEl.querySelector('.service-id-input')?.value || '';
                    if (!idVal.trim()) {
                        serviceEl.querySelector('.service-id-input').classList.add('is-invalid');
                        valid = false;
                    } else {
                        serviceEl.querySelector('.service-id-input').classList.remove('is-invalid');
                    }
                    group.services.push({
                        id: idVal,
                        title: serviceEl.querySelector('.service-title-input')?.value || '',
                        desc: serviceEl.querySelector('.service-desc-input')?.value || '',
                        status: serviceEl.querySelector('.service-status-select')?.value || 'online',
                        avatar: serviceEl.querySelector('.service-avatar-input')?.value || '',
                        qrcode: serviceEl.querySelector('.service-qrcode-input')?.value || '',
                        tip: serviceEl.querySelector('.service-tip-input')?.value || '',
                        link: serviceEl.querySelector('.service-link-input')?.value || ''
                    });
                });
                groups.push(group);
            });
            if (!valid) {
                alert('ID不能为空');
                return;
            }
            const configData = {
                merchant_name: document.getElementById('merchant_name').value,
                phone: document.getElementById('phone').value,
                groups: groups
            };
            document.getElementById('groupsInput').value = JSON.stringify(configData);
            this.submit();
        });
    });
// 图片上传处理函数（保持原有实现）
async function handleImageUpload(button, type) {
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = 'image/*';
    fileInput.onchange = async function() {
        if (!this.files.length) return;
        const file = this.files[0];
        const formData = new FormData();
        formData.append('file', file);
        formData.append('uid', '{{req.session.totemUID}}');
        formData.append('code', 'mta-helpdesk');
        try {
            const response = await fetch('https://mall.totembio.cn/api/uploadMtaFile', {
                method: 'POST',
                body: formData
            });
            const result = await response.json();
            if (result.status == 200 && result.data && result.data.src) {
                const input = button.previousElementSibling;
                input.value = result.data.src;
                // 立即刷新预览
                let img;
                if (type === 'avatar') {
                    img = button.parentElement.querySelector('.avatar-preview');
                } else if (type === 'qrcode') {
                    img = button.parentElement.querySelector('.qrcode-preview');
                }
                if (img) {
                    img.src = result.data.src;
                    img.style.display = '';
                }
            } else {
                alert('上传失败: ' + (result.message || '未知错误'));
            }
        } catch (error) {
            alert('上传失败: ' + error.message);
        }
    };
    fileInput.click();
}
</script>
</body>
</html>
